package com.gin.pixiv.deserializer

import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.TreeNode
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer

/**
 * 将对象字段中的数字key解析为Long列表
 * @author BX-Gin
 * @since 2024/3/2 12:54
 */
class LongKeyListDeserializer : JsonDeserializer<List<Long>>() {
    override fun deserialize(jsonParser: JsonParser?, ctxt: DeserializationContext?): List<Long>? {
        val rootNode = jsonParser?.readValueAsTree<TreeNode>()

        if (rootNode?.isObject != true) {
            return null
        }
        val list = arrayListOf<Long>()

        val it = rootNode.fieldNames()
        while (it.hasNext()) {
            val key = it.next().toLongOrNull()
            if (key != null) list.add(key)
        }
        return list
    }
}